package utils;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileOutputStream;

public class PdfUtil {
	private static final Log log = LogFactory.getLog(PdfUtil.class);
	
	private static Document document;

    private static Font keyfont;// 设置字体大小
    
    private static PdfWriter writer;
    
    /**
     * 生成文件
     * @param file 待生成的文件名
     */
    public static Document CreatePdf(String filePath){
    	document = new Document(PageSize.A4);// 建立一个Document对象
        try
        {
        	writer = PdfWriter.getInstance(document, new FileOutputStream(filePath));
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
            keyfont = new Font(bfChinese, 12, Font.BOLD);// 设置字体大小
            document.open();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return document;
    }
    
    /**
     * 关闭资源
     */
    public static void close(Document doc,PdfWriter writer){
    	doc.close();
    	writer.close();
    }
    
    /**
     * 新增普通的一行
     * @param value
     * @param font
     * @return
     */
    public static PdfPCell createCell(String value, Font font) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //水平居中
        cell.setHorizontalAlignment(Element.ALIGN_CENTER); //垂直居中
	    cell.setMinimumHeight(30);
        cell.setPhrase(new Phrase(value, font));
        return cell;
	}

	/**
	 * 新增指定行数的一行
	 * @param value	值
	 * @param font	字体
	 * @param rowspan	占多少行
	 * @return
	 */
	public static PdfPCell createCellRowspan(String value, Font font, int rowspan) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //水平居中
        cell.setHorizontalAlignment(Element.ALIGN_CENTER); //垂直居中
	    cell.setMinimumHeight(30);
        cell.setPhrase(new Phrase(value, font));
	    cell.setRowspan(rowspan);
        return cell;
	}

	/**
	 * 新增指定列数的一行
	 * @param value	值
	 * @param font	字体
	 * @param rowspan	占多少列
	 * @return
	 */
	public static PdfPCell createCellColspan(String value, Font font, int colspan) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //水平居中
        cell.setHorizontalAlignment(Element.ALIGN_CENTER); //垂直居中
	    cell.setMinimumHeight(30);
        cell.setPhrase(new Phrase(value, font));
	    cell.setColspan(colspan);
        return cell;
	}

	public static Font getKeyfont() {
		return keyfont;
	}

	public static PdfWriter getWriter() {
		return writer;
	}

	public static void setWriter(PdfWriter writer) {
		PdfUtil.writer = writer;
	}
}
